<?php
/**
 * PhpStorm
 * User: zucheng
 * Date: 2019/3/24
 */

namespace App\Http\Controllers\Api\V1;

use Validator;
use App\Http\Controllers\Api\ApiController;
use App\Models\CarScheme;
use App\Models\CarSite;
use Illuminate\Http\Request;

class CarController extends ApiController
{
    /**
     * 车辆型号查询
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function siteList(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'site_type' => 'required|integer',
            ]);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            $fields = [
                'id as site_id',
                'site_key',
                'site_value',
                'site_type',
            ];
            $sites  = CarSite::select($fields)
                ->where('site_type', $request->get('site_type'))
                ->where('site_status', CarSite::STATUS_YES)
                ->get()
                ->toArray();

            return $this->success('success', $sites);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 新建车辆方案
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addScheme(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'model_site_id'  => 'required|integer',
                'box_site_id'    => 'required|integer',
                'length_site_id' => 'required|integer',
            ]);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            $data   = [
                'model_site_id'  => $request->get('model_site_id'),
                'box_site_id'    => $request->get('box_site_id'),
                'length_site_id' => $request->get('length_site_id'),
            ];
            $scheme = CarScheme::firstOrCreate($data, $data);
            if (!$scheme) {
                return $this->error('创建车辆方案失败');
            }

            return $this->success('success', ['car_scheme_id' => $scheme->id]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

}